﻿using System;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using Texfina.Core.Common;
using Texfina.Core.Web;
using Texfina.Common.Mg;
using Texfina.Common.Rh;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using System.Text;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using CrystalDecisions.Shared;
using System.Web.UI;
using RHBORpt = Texfina.BORpt.Rh;

namespace RH
{
    public partial class wfTRegistroRpt : SearchPage
    {
        public const int _GRDLIST_STEXPORTA = 4;

        protected void Page_Load(object sender, EventArgs e)
        {

            this.LoadInitialSettings();
            if (this.IsPostBack)
            {
                this.LoadInPostBack();
                return;
            }

            this.LoadData();
            SearchData();

        }

        public override void LoadInitialSettings()
        {
            Label lbl = (Label)this.Master.FindControl("lblTitle");
            lbl.Text = "Exportar PDT";
        }

        public override void LoadListControls()
        {
            ETablaGenDet objEDet = new ETablaGenDet();
            MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));

            objEDet.IdTabla = ConstMultitabla.MES;
            DataTable dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidMes, dt, "dsDescrip", "idCodigo");

        }
        public override void SearchData()
        {
            ETRegistro objE = new ETRegistro();
            IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.TRegistro));
            DataTable dt = objBO.GetList(objE);
            this.GridSetDataBinding(grdList, dt);

        }

        public override void RegisterGeneralScripts()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("function validateEditForm(key){");
            sb.AppendLine("debugger;");

            sb.AppendLine("varRpta = isEmptyCheckBox();");
            sb.AppendLine("if(varRpta == false)");
            sb.AppendLine("  return false;");
            sb.AppendLine("menu_doPostBack('" + this.mnuToolbar.ClientID + "','" + this.mnuToolbar.UniqueID + "',key);");
            sb.AppendLine("}");

            ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);

        }


        protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
        {
            if (e.Item == null)
                return;

            switch (e.Item.Value)
            {
                case ConstMenuToolbarValue.BUTTON_PRINT:
                    PrintReport("");
                    break;
                case ConstMenuToolbarValue.BUTTON_EXPORT:
                    ExportReport("");
                    break;
            }

        }

        protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                CheckBox chkAllChecked = new CheckBox();
                chkAllChecked.ID = "chkAllCheck";
                chkAllChecked.Checked = false;
                chkAllChecked.Attributes.Add("onClick", "SelectedCheckBoxAll(this);");
                e.Row.Cells[0].Controls.Add(chkAllChecked);
            }

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                String strRI = e.Row.RowIndex.ToString();
                ImageButton bttprint = (ImageButton)e.Row.FindControl("grdBtt" + ConstGridRowCommand.GRIDPREVIEW);
                bttprint.OnClientClick = "javascript:return validateGridCommands('" + ConstGridRowCommand.GRIDCHECK + "','" + strRI + "');";

                if (e.Row.Cells[_GRDLIST_STEXPORTA].Text == ConstFlagEstado.ACTIVADO)
                {
                    bttprint.ImageUrl = "../Images/Icons/Disabled/Sunat.png";
                }

            }

        }

        protected void grdBttCmdPrevPostBackDataBinding(Object sender, EventArgs e)
        {
            ImageButton ctl = (ImageButton)sender;
            ScriptManager sm = ScriptManager.GetCurrent(this.Page);
            sm.RegisterPostBackControl(ctl);
        }

        protected void grdList_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            DataRow dr = this.GridGetRowFromDataKey(grdList, Convert.ToInt32(e.CommandArgument));

            switch (e.CommandName)
            {
                case ConstGridRowCommand.GRIDPREVIEW:

                    if (dr["stExporta"].ToString() == ConstFlagEstado.DESACTIVADO)
                    {
                        this.PrintReport(dr["idTRegistro"].ToString());
                    }
                    else
                    {
                        this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, "Esta opcion no esta Habilitada", "");
                    }
                    return;
            }
        }

        public override void PrintReport(string key)
        {
            DataSet ds = (DataSet)this.GetDataReport(key);

            if (ds.Tables[0].Rows.Count == 0)
            {
                this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, "No se encotraron Resultados", "");
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "msgPB", "MessageOnPostback();", true);
                return;
            }

            Response.Clear();

            switch (key)
            {
                case "05":
                    Response.AddHeader("Content-Disposition", "attachment;filename=RP_" + ds.Tables[0].Rows[0]["nu_ruc"].ToString() + ".est");
                    break;
                case "11":
                    Response.AddHeader("Content-Disposition", "attachment;filename=0601" + Session[ConstSessionVar.PERIODO].ToString() + ddlidMes.SelectedItem.Value.Substring(1, 2) + ds.Tables[0].Rows[0]["nu_ruc"].ToString() + ".jor");
                    break;
                case "13":
                    Response.AddHeader("Content-Disposition", "attachment;filename=0601" + Session[ConstSessionVar.PERIODO].ToString() + ddlidMes.SelectedItem.Value.Substring(1, 2) + ds.Tables[0].Rows[0]["nu_ruc"].ToString() + ".rem");
                    break;
                default:
                    return;
            }

            Response.Buffer = true;
            Response.ContentType = "text/plain";

            StringBuilder sb = new StringBuilder();

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                sb.AppendLine(dr["item"].ToString());
            }

            Response.Write(sb.ToString());
            Response.Flush();
            Response.End();

        }

        public override void ExportReport(string key)
        {
            
            DataSet ds = (DataSet)this.GetDataExporta(key);
            
            if (ds.Tables[0].Rows.Count == 0)
            {
                this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, "No se encotraron Resultados", "");
                return;
            }
            ExcelHelper.ToExcel(ds, "PDT.xls", Response);

        }

        public override object GetDataReport(string key)
        {
            ETRegistroReporte objEDet = new ETRegistroReporte();
            RHBORpt.ITRegistro objBODet = (RHBORpt.ITRegistro)WCFHelper.GetObject<RHBORpt.ITRegistro>(typeof(RHBORpt.TRegistro));
            objEDet.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
            objEDet.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objEDet.IdMes = ddlidMes.SelectedItem.Value;
            objEDet.IdStore = key;
            DataTable dt = objBODet.GetDataXKey(objEDet);
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            return ds;
        }

        public object GetDataExporta(string key)
        {
            DataSet ds = new DataSet();
            foreach (GridViewRow gvr in this.grdList.Rows)
            {
                if (gvr.RowType == DataControlRowType.DataRow)
                {
                    if (((CheckBox)gvr.FindControl("chkSelected")).Checked)
                    {
                        ETRegistroReporte objEDet = new ETRegistroReporte();
                        RHBORpt.ITRegistro objBODet = (RHBORpt.ITRegistro)WCFHelper.GetObject<RHBORpt.ITRegistro>(typeof(RHBORpt.TRegistro));
                        objEDet.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
                        objEDet.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                        objEDet.IdMes = ddlidMes.SelectedItem.Value;
                        objEDet.IdStore = gvr.Cells[2].Text;
                        DataTable dt = objBODet.GetDataXKey(objEDet);
                        dt.TableName = gvr.Cells[5].Text.Trim();

                        ds.Tables.Add(dt);
                    }

                }
            }
            
            return ds;
            
        }
    }
}